from flask import  Blueprint,render_template,url_for,request,redirect,jsonify

from blueprints.user_page import add_record
from models.House import House
from sqlalchemy import func
from flask import Flask
import math
from datetime import datetime, timedelta
from utils.regression_data import linear_model_main

bp = Blueprint('detail_page',__name__,url_prefix='/')

@bp.route('/house/<int:hid>')
def detail(hid):
    # 获取类型相似房源信息

    # 从数据库查询房源ID为hid的房源对象
    house = House.query.get(hid)

    # 处理配套设施字符串为列表
    username=request.cookies.get('username')
    if(username):add_record(hid,username)
    facilitise_str = house.facilities
    facilitise_list = facilitise_str.split('-')

    # 查询推荐房源
    # 提取当前房源的户型、区域和价格信息
    target_rooms = house.rooms
    target_address = house.address
    try:
        target_price = int(house.price)
    except (ValueError, TypeError):
        target_price = 3000

    price_diff = 2000  # 价格差异范围

    # 查询符合条件的推荐房源
    recommend_houses = House.query.filter(
        House.id != hid,  # 排除当前房源
        House.rooms == target_rooms,  # 户型相同
        House.address.contains(target_address),  # 区域相同（假设address包含区域信息）
        House.price.between(target_price - price_diff, target_price + price_diff)  # 价格差异在2000以内
    ).order_by(House.publish_time.desc()).limit(6).all()  # 取6条最新的

    return render_template('detail_page.html',
                           house=house,
                           facilitise=facilitise_list,
                           recommend_houses=recommend_houses)  # 传递推荐房源到模板

# 自定义过滤器，用于处理交通条件有无数据的情况

def deal_traffic_txt(word):
    if len(word) == 0 or word is None:
        return '暂无信息！'
    else:
        return word
bp.add_app_template_filter(deal_traffic_txt, 'dealNone')

@bp.route("/get/echarts_test")
def echarts_test():
    return render_template("echarts_test.html")

@bp.route("/get/piedata/<block>")
def return_pie_data(block):
    # 查找与该房源同一街道的其他房子的户型占比
    result = (House.query.with_entities(House.rooms,func.count())
              .filter(House.block == block)
              .group_by(House.rooms)
              .order_by(func.count().desc()).all())
    data = []
    for  one_house in result:
        data.append({'name':one_house[0], 'value':one_house[1]})
    return jsonify({'data':data})

@bp.route("/get/columndata/<block>")
def return_bar_data(block):
    result = (House.query.with_entities(House.address,func.count())
              .filter(House.block == block)
              .group_by(House.address)
              .order_by(func.count().desc()).all())
    name_list = []
    num_list = []
    for addr,num in result:
        residence_name = addr.split('-')[2] #提取出小区名称
        name_list.append(residence_name)
        num_list.append(num)
    if len(name_list) > 20:
        data = {'name_list_x': name_list[:20], 'num_list_y': num_list[:20]}
    else:
        data = {'name_list_x': name_list, 'num_list_y': num_list}
    return jsonify({'data': data})
# 实现户型价格走势

@bp.route('/get/brokenlinedata/<block>')
def return_brokenline_data(block):
    # 时间序列
    time_stamp = House.query.filter(House.block == block).with_entities(House.publish_time).all()
    time_stamp.sort(reverse=True)
    date_li = []
    # date_li.append(datetime.fromtimestamp(int(time_stamp[0][0])).strftime("%m-%d"))
    for i in range(1, 14):
        latest_release = datetime.fromtimestamp(int(time_stamp[0][0]))
        day = latest_release + timedelta(days=-i)
        date_li.append(day.strftime("%m-%d"))
    date_li.reverse()
    # 1室1厅的户型
    result = House.query.with_entities(func.avg(House.price / House.area)).filter(House.block == block,
                                                                                  House.rooms == '1室1厅').group_by(
        House.publish_time).order_by(House.publish_time).all()
    data = []
    for i in result[-14:]:
        data.append(round(i[0], 2))
    # 2室1厅的户型
    result1 = House.query.with_entities(func.avg(House.price / House.area)).filter(House.block == block,
                                                                                   House.rooms == '2室1厅').group_by(
        House.publish_time).order_by(House.publish_time).all()
    data1 = []
    for i in result1[-14:]:
        data1.append(round(i[0], 2))
    # 2室2厅的户型
    result2 = House.query.with_entities(func.avg(House.price / House.area)).filter(House.block == block,
                                                                                   House.rooms == '2室2厅').group_by(
        House.publish_time).order_by(House.publish_time).all()
    data2 = []
    for i in result2[-14:]:
        data2.append(round(i[0], 2))
    # 3室2厅的户型
    result3 = House.query.with_entities(func.avg(House.price / House.area)).filter(House.block == block,
                                                                                   House.rooms == '3室2厅').group_by(
        House.publish_time).order_by(House.publish_time).all()
    data3 = []
    for i in result3[-14:]:
        data3.append(round(i[0], 2))
    return jsonify({'data': {'1室1厅': data, '2室1厅': data1, '2室2厅': data2, '3室2厅': data3, 'date_li': date_li}})

# 实现房价预测功能

@bp.route('/get/scatterdata/<block>')
def return_scatter_data(block):
    # 获取时间序列
    result = House.query.with_entities(func.avg(House.price / House.area)).filter(House.block == block).group_by(
        House.publish_time).order_by(House.publish_time).all()
    time_stamp = House.query.filter(House.block == block).with_entities(House.publish_time).all()
    time_stamp.sort(reverse=True)
    date_li = []

    for i in range(1, 30):
        latest_release = datetime.fromtimestamp(int(time_stamp[0][0]))
        day = latest_release + timedelta(days=-i)
        date_li.append(day.strftime("%m-%d"))
    date_li.reverse()

    # 获取平均价格
    data = []
    x = []
    y = []

    for index, i in enumerate(result):
        x.append([index])
        y.append(round(i[0], 2))
        data.append([index, round(i[0], 2)])

    # 对未来一天的价格进行预测

    predict_value = len(data)
    predict_outcome = linear_model_main(x, y, predict_value)
    p_outcome = round(predict_outcome[0], 2)

    # 将预测的数据添加入data中
    data.append([predict_value, p_outcome])
    return jsonify({'data': {'data-predict': data, 'date_li': date_li}})